package com.tiyende.credit.loop.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.base.app.TiyendeActivityStackManager
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.configs.TiyendeConfigs
import com.tiyende.credit.loop.databinding.TiyendeActivityOrderInfoBinding
import com.tiyende.credit.loop.event.TiyendeEventData
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.ui.adapter.TIyendeOrderInfoAccountAdapter
import com.tiyende.credit.loop.ui.contract.IViewContract
import com.tiyende.credit.loop.ui.dialog.TiyendeAccountOrderInfoOnlyOneDialog
import com.tiyende.credit.loop.ui.dialog.TiyendeTipsDialog
import com.tiyende.credit.loop.ui.dialog.TiyendeUserDataClearDialog
import com.tiyende.credit.loop.ui.presenter.TiyendeOrderDetailsPresenter
import com.tiyende.credit.loop.utils.TiyendeDensityUtil
import com.tiyende.credit.loop.utils.decoration.LinearSpacingItemDecoration
import com.tiyende.credit.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.credit.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.math.BigDecimal

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/19 10:57
 * @Annotation：订单详情
 */
class TiyendeOrderInfoActivity: CommonActivity(),IViewContract.ITiyendeOrderInfoView {
    lateinit var binding: TiyendeActivityOrderInfoBinding
    private var eventRemark = ""
    private var presenter: TiyendeOrderDetailsPresenter? = null
    private var accountAdapter: TIyendeOrderInfoAccountAdapter? = null

    companion object {
        private const val INTENT_KEY_ORDERID = "orderId"
        fun start(context: Context,orderId: String) {
            val intent = Intent(context, TiyendeOrderInfoActivity::class.java)
            intent.putExtra(INTENT_KEY_ORDERID, orderId)
            context.startActivity(intent)
        }
    }

    override fun getTiyendeRootView(): View? {
        binding = TiyendeActivityOrderInfoBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeTextTitleVisibility(View.GONE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        initOrderDetailsRefrashView()
        initOrderDetailsAccountRecyclerView()
        binding.orderDetailsLayout.visibility = View.INVISIBLE
    }

    override fun initTiyendeListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,eventRemark)
        }
        //新增账户
        binding.btOrderInfoAccountAdd.setOnClickListener {
            onIntent(TiyendeAuthenticationAccountCreateActivity::class.java)
        }
        //清除用户数据
        binding.btDataClear.setOnClickListener {
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_DATA_CLEAR,"Order Rejected")
            showUserClearDataDialog()
        }
    }

    override fun loadTiyendeData() {
        if (presenter == null){
            presenter = TiyendeOrderDetailsPresenter(this)
        }
        showTiyendeLoading()
        presenter?.loadOrderDetailsAction()
    }

    /* 初始化刷新 */
    private fun initOrderDetailsRefrashView() {
        binding.orderDetailsRefreshView.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.orderDetailsRefreshView.setOnRefreshListener {
            presenter?.loadOrderDetailsAction()
        }
    }

    /**
     * 初始化Views
     */
    private fun initOrderDetailsAccountRecyclerView(){
        binding.rvReceiveAccount.isNestedScrollingEnabled = false
        binding.rvReceiveAccount.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.rvReceiveAccount.layoutManager = layoutManager
        val topDecoration = TiyendeDensityUtil.dp2px(16f)
        binding.rvReceiveAccount.addItemDecoration(LinearSpacingItemDecoration(0, 0,topDecoration,topDecoration))
        accountAdapter = TIyendeOrderInfoAccountAdapter(binding.rvReceiveAccount)
        binding.rvReceiveAccount.adapter = accountAdapter
        binding.rvReceiveAccount.itemAnimator = DefaultItemAnimator()
        accountAdapter?.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter?.getItem(position)

        }
    }

    /**
     * 获取订单id
     */
    override fun getTiyendeOrderInfoId(): String{
        return intent.extras?.getString(INTENT_KEY_ORDERID).toString()
    }

    /**
     * 共用Views
     */
    @SuppressLint("SetTextI18n")
    override fun showTiyendeOrderInfoCommonViews(obj: JSONObject) {
        //刷新订单列表 - 防止状态差异
        publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESH))

        binding.orderInfoTipsLayout.visibility = View.GONE
        binding.orderInfoAccountAddLayout.visibility = View.GONE
        //法语地区才显示添加绑卡账户按钮
        if (TiyendeConfigs.isFrench()){
            binding.orderInfoTipsLayout.visibility = View.VISIBLE
            binding.orderInfoAccountAddLayout.visibility = View.VISIBLE
        }

        binding.textApplyAmount.text = "${BigDecimal(obj.optString("amount")).stripTrailingZeros().toPlainString()} ${obj.optString("currency")}"
        binding.textApplyTerm.text = String.format(getString(R.string.tiyende_order_details_repayment_term_days),obj.optString("days"))
        binding.orderDetailsLayout.visibility = View.VISIBLE
    }

    /**
     * 审核中
     */
    override fun showTiyendeOrderInfoReviewingViews() {
        binding.imgOrderStatus.setImageResource(R.mipmap.tiyende_order_info_inreviewing_icon)
        binding.textOrderStatus.text = getString(R.string.tiyende_order_status_in_review)
        binding.textOrderStatus.setTextColor(Color.parseColor("#FF3ED9AB"))
        binding.textOrderStatusTips.setTextColor(Color.parseColor("#FFAAAAAA"))

        val showApproveTime = getString(R.string.tiyende_order_details_reviewing_approve_time)
        val showContactTime = getString(R.string.tiyende_order_details_reviewing_contact_time)
        val showTips = String.format(getString(R.string.tiyende_order_details_reviewing_tips),showApproveTime,showContactTime)
        val index1 = showTips.indexOf(showApproveTime)
        val index2 = showTips.indexOf(showContactTime)
        val spString = SpannableString(showTips)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF3ED9AB")), index1, index1 + showApproveTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF3ED9AB")), index2, index2 + showContactTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textOrderStatusTips.text = spString

        //显示收款账户列表
        binding.rvReceiveAccount.visibility = View.VISIBLE
        presenter?.loadScoreCommentAction()
        //不显示清除用户数据按钮
        binding.btDataClear.visibility = View.GONE

        //根据配置显示公告信息
        showTiyendeConfigNoticeDialog()
    }

    /**
     * 放款中
     */
    override fun showTiyendeOrderInfoDisbursingViews() {
        binding.imgOrderStatus.setImageResource(R.mipmap.tiyende_order_info_inprogress_icon)
        binding.textOrderStatus.text = getString(R.string.tiyende_order_status_payment_in_progress)
        binding.textOrderStatus.setTextColor(Color.parseColor("#FFFA8D44"))
        binding.textOrderStatusTips.text = getString(R.string.tiyende_order_details_disbursing_tips)
        binding.textOrderStatusTips.setTextColor(Color.parseColor("#FFAAAAAA"))
        binding.textOrderStatusTips.visibility = View.INVISIBLE

        //显示收款账户列表
        binding.rvReceiveAccount.visibility = View.VISIBLE
        presenter?.loadScoreCommentAction()
        //不显示清除用户数据按钮
        binding.btDataClear.visibility = View.GONE

        //根据配置显示公告信息
        showTiyendeConfigNoticeDialog()
    }

    /**
     * 已拒绝
     */
    override fun showTiyendeOrderInfoRejectedViews(obj: JSONObject) {
        binding.imgOrderStatus.setImageResource(R.mipmap.tiyende_order_info_rejected_icon)
        binding.textOrderStatus.text = getString(R.string.tiyende_order_status_rejected)
        binding.textOrderStatus.setTextColor(Color.parseColor("#FFFF4444"))
        binding.textOrderStatusTips.setTextColor(Color.parseColor("#FFFF4231"))

        var againApplyDate = obj.optString("againApplyDate","")
        if (againApplyDate.isEmpty()){
            againApplyDate = TiyendeProcessHelper.queryTiyendeAuthenticationApplyAgainDate()
        }
        binding.textOrderStatusTips.text = String.format(getString(R.string.tiyende_order_details_rejected_tips),againApplyDate)

        binding.orderInfoTipsLayout.visibility = View.GONE
        binding.orderInfoAccountAddLayout.visibility = View.GONE
        //不显示收款账户
        binding.rvReceiveAccount.visibility = View.GONE

        //不显示清除用户数据按钮
        binding.btDataClear.visibility = View.GONE
    }

    /**
     * 待还款
     */
    override fun showTiyendeOrderInfoRepayViews() {
        //显示待还款列表
        publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_SHOW_REPAY))
        launch(Dispatchers.Main){
            delay(1000)
            //刷新订单列表
            publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESH))
            TiyendeActivityStackManager.finishAllActivity(TiyendeMainActivity::class.java)
        }
    }

    /**
     * 是否显示清除用户数据按钮
     */
    override fun showTiyendeUserDataClearButton(isShow: Boolean) {
        if (isShow){
            binding.btDataClear.visibility = View.VISIBLE
        } else {
            binding.btDataClear.visibility = View.GONE
        }
    }

    /**
     * 清除用户数据成功，退出APP重新登录
     */
    override fun showTiyendeUserDataClearSuccess() {
        //退出登录，需要移除用户保存的信息
        TiyendeSharedHelper.onTiyendeLoginOut()
        onIntent(TiyendeLoginActivity::class.java)
    }

    override fun showTiyendeOrderInfoWalletList(accountList: ArrayList<JSONObject>) {
        accountAdapter?.data = accountList

        //法语地区 && 绑卡账户只有一个，需要提示
        if (TiyendeConfigs.isFrench() && accountList.size == 1){
            showTiyendeOrderInfoAccountOnlyOneDialog()
        }
    }

    /**
     * 法语地区 绑卡账户只有一个提示
     */
    private fun showTiyendeOrderInfoAccountOnlyOneDialog(){
        val accountOnlyOneDialog = TiyendeAccountOrderInfoOnlyOneDialog(this,eventRemark,object : TiyendeAccountOrderInfoOnlyOneDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.btOrderInfoAccountAdd -> {//继续添加
                        binding.btOrderInfoAccountAdd.callOnClick()
                    }
                }
            }
        })
        accountOnlyOneDialog.setCancelable(true)
        accountOnlyOneDialog.setCanceledOnTouchOutside(true)
        accountOnlyOneDialog.show()
    }

    /**
     * 审核中、放款中 根据配置显示公告Dialog
     */
    private fun showTiyendeConfigNoticeDialog(){
        if (isFinishing || isDestroyed){
            return
        }
        if (!TiyendeConfigsHelper.isTiyendeShowConfigNotice()){
            return
        }

        val noticeInfo = TiyendeConfigsHelper.queryTiyendeConfigNoticeInfo() ?: return
        val maxNum = noticeInfo.optInt("num",1)
        val showNum = TiyendeConfigsHelper.showNoticeNum
        //本地记录的显示公告次数 >= 配置次数
        if (showNum >= maxNum){
            return
        }
        TiyendeConfigsHelper.showNoticeNum = showNum + 1

        val noticeDialog = TiyendeTipsDialog(this)
        noticeDialog.setCancelable(true)
        noticeDialog.setCanceledOnTouchOutside(true)
        noticeDialog.show()
        noticeDialog.isTiyendeDoubleButton(false)
        noticeDialog.addTiyendeTipsIconResource(R.mipmap.tiyende_dialog_tips_icon)
        noticeDialog.addTiyendeBtnOkText(getString(R.string.tiyende_button_confirm))
        var noticeTitle = noticeInfo.optString("noticeTitle")
        var noticeText = noticeInfo.optString("noticeText")
        //高棉语
        if (TiyendeSharedHelper.queryTiyendeSharedString(TiyendeSharedKey.TIYENDE_LANGUAGE_TAGS) == "km"){
            if (noticeInfo.optString("noticeTitle_km","").isNotEmpty()){
                noticeTitle = noticeInfo.optString("noticeTitle_km")
            }
            if (noticeInfo.optString("noticeText_km","").isNotEmpty()){
                noticeText = noticeInfo.optString("noticeText_km")
            }
        }
        noticeDialog.addTiyendeTitleText(noticeTitle)
        noticeDialog.addTiyendeTipsText(noticeText)
    }

    /**
     * 清空用户数据dialog
     */
    private fun showUserClearDataDialog(){
        val clearDialog = TiyendeUserDataClearDialog(this,object : TiyendeUserDataClearDialog.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                showTiyendeLoading()
                presenter?.loadUserClearDataAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        //刷新已添加账户列表
        if (event.eventType == TiyendeEventData.TYPE.TIYENDE_WALLET_REFRESH){
            presenter?.loadOrderDetailsAction()
        }
    }

    override fun hiddenTiyendeLoading() {
        super.hiddenTiyendeLoading()
        binding.orderDetailsRefreshView.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "OrderDetails Page ${getTiyendeOrderInfoId()}"
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_ORDER_DETAILS_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_ORDER_DETAILS_END,eventRemark)
    }
}